package cn.smile.business.basic.impl;

import cn.smile.bean.dto.basic.BasicItemDTO;
import cn.smile.bean.dto.basic.ExpenseItemDTO;
import cn.smile.bean.dto.basic.MyShopDTO;
import cn.smile.bean.dto.core.SysUserDTO;
import cn.smile.bean.entity.basic.BasicItem;
import cn.smile.bean.form.basic.item.BasicItemAddForm;
import cn.smile.bean.form.basic.item.BasicItemUpdateForm;
import cn.smile.bean.form.basic.item.QueryBasicItemForm;
import cn.smile.bean.form.basic.item.QueryItemForm;
import cn.smile.bean.form.core.user.QueryUserForm;
import cn.smile.business.basic.IBasicItemService;
import cn.smile.business.basic.IExpenseItemService;
import cn.smile.business.basic.IMyShopService;
import cn.smile.business.core.ISysUserService;
import cn.smile.commons.constant.NumberConstant;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.commons.exceptions.BusinessException;
import cn.smile.commons.response.MyResponseCode;
import cn.smile.repository.basic.BasicItemMapper;
import cn.smile.utils.BeanCopy;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class BasicItemServiceImpl extends BaseServiceImpl<BasicItemMapper, BasicItem> implements IBasicItemService {
    @Resource
    private IMyShopService shopService;
    @Resource
    private ISysUserService userService;
    @Resource
    private IExpenseItemService itemService;

    @Override
    public Boolean addBasicItem(BasicItemAddForm form) {
        log.info("[BasicItemServiceImpl].[addBasicItem] ------> 新增基础项目 Start, form = {}", JSON.toJSONString(form));
        BasicItem entity = BeanCopy.copyBean(form, BasicItem.class);
        super.addBaseCol(entity);
        MyShopDTO shop = shopService.getMyShop();
        entity.setShopId(shop.getId());
        boolean flag = super.create(entity);
        log.info("[BasicItemServiceImpl].[addBasicItem] ------> 新增基础项目 End, flag = {}", flag);
        return flag;
    }

    @Override
    public Boolean updateBasicItem(BasicItemUpdateForm form) {
        log.info("[BasicItemServiceImpl].[updateBasicItem] ------> 更新基础项目 Start, form = {}", JSON.toJSONString(form));
        BasicItem entity = BeanCopy.copyBean(form, BasicItem.class);
        boolean flag = super.update(entity);
        log.info("[BasicItemServiceImpl].[updateBasicItem] ------> 更新基础项目 End, flag = {}", flag);
        return flag;
    }

    @Override
    public IPage<BasicItemDTO> getPage(QueryBasicItemForm form) {
        log.info("[BasicItemServiceImpl].[getPage] ------> 分页查询基础项目 Start, form = {}", JSON.toJSONString(form));
        LambdaQueryWrapper<BasicItem> qw = this.getQueryParams(form);
        Page<BasicItem> basePage = baseMapper.selectPage(form.queryPage(), qw);
        IPage<BasicItemDTO> dataPage = BeanCopy.copyPage(basePage, BasicItemDTO.class);
        this.setDetail(dataPage.getRecords());
        log.info("[BasicItemServiceImpl].[getPage] ------> 分页查询基础项目 End");
        return dataPage;
    }

    @Override
    public BasicItemDTO getBaseItemById(String id) {
        log.info("[BasicItemServiceImpl].[getBaseItemById] ------> 查询基础项目信息 Start, id = {}", id);
        BasicItem entity = super.get(id);
        BasicItemDTO dto = BeanCopy.copyBean(entity, BasicItemDTO.class);
        this.setDetail(Lists.newArrayList(dto));
        log.info("[BasicItemServiceImpl].[getBaseItemById] ------> 查询基础项目信息 End");
        return dto;
    }

    @Override
    public Boolean delBaseItem(String id) {
        log.info("[BasicItemServiceImpl].[delBaseItem] ------> 删除基础项目 Start, id = {}", id);
        QueryItemForm queryForm = new QueryItemForm();
        queryForm.setBasicId(id);
        List<ExpenseItemDTO> itemList = itemService.getItemList(queryForm);
        if (!CollectionUtils.isEmpty(itemList)) {
            throw new BusinessException(MyResponseCode.BUSINESS_ERROR, String.format("消费单[%s]存在该项目", itemList.get(NumberConstant.ZERO).getItemName()));
        }
        boolean delFlag = super.delById(id);
        log.info("[BasicItemServiceImpl].[delBaseItem] ------> 删除基础项目 End, delFlag = {}", delFlag);
        return delFlag;
    }

    @Override
    public List<BasicItemDTO> getList(QueryBasicItemForm form) {
        log.info("[BasicItemServiceImpl].[getList] ------> 列表查询基础项目 Start, form = {}", JSON.toJSONString(form));
        LambdaQueryWrapper<BasicItem> qw = this.getQueryParams(form);
        qw.orderByAsc(BasicItem::getSortNumber);
        List<BasicItem> baseList = baseMapper.selectList(qw);
        List<BasicItemDTO> dataList = BeanCopy.copyList(baseList, BasicItemDTO.class);
        this.setDetail(dataList);
        log.info("[BasicItemServiceImpl].[getList] ------> 列表查询基础项目 End");
        return dataList;
    }

    /**
     * 写入详情数据
     *
     * @param dataList 数据集合
     */
    private void setDetail(List<BasicItemDTO> dataList) {
        if (!CollectionUtils.isEmpty(dataList)) {
            Set<String> userIds = new HashSet<>(NumberConstant.EIGHT);
            dataList.forEach(data -> {
                if (!ObjectUtils.isEmpty(data.getOpeUserId())) {
                    userIds.add(data.getOpeUserId());
                }
            });
            QueryUserForm userForm = new QueryUserForm();
            userForm.setIds(Lists.newArrayList(userIds));
            Map<String, SysUserDTO> userMap = userService.getMyShopUserMap(userForm);

            for (BasicItemDTO dto : dataList) {
                if (!ObjectUtils.isEmpty(dto.getOpeUserId()) && userMap.containsKey(dto.getOpeUserId())) {
                    SysUserDTO user = userMap.get(dto.getOpeUserId());
                    dto.setOpeUser(user);
                    dto.setOpeUserName(user.getNickName());
                }
            }
        }
    }

    /**
     * 组装查询参数
     *
     * @param form 查询参数
     * @return 查询对象
     */
    private LambdaQueryWrapper<BasicItem> getQueryParams(QueryBasicItemForm form) {
        MyShopDTO shop = shopService.getMyShop();
        LambdaQueryWrapper<BasicItem> qw = new QueryWrapper<BasicItem>().lambda().eq(BasicItem::getDeleted, Boolean.FALSE);
        qw.eq(BasicItem::getShopId, shop.getId());
        if (!ObjectUtils.isEmpty(form.getBaseName())) {
            qw.like(BasicItem::getBaseName, form.getBaseName());
        }
        if (!CollectionUtils.isEmpty(form.getIds())) {
            qw.in(BasicItem::getId, form.getIds());
        }
        return qw;
    }
}
